﻿using BLL;
using Model;
using System;
using System.Data;
using System.Text;
using System.Web.UI.WebControls;

namespace Thksoft.BusinessExpansion.Process
{
    public partial class SelectProcessUser : System.Web.UI.Page
    {
        private Lc_ProcessBLL lpb = new Lc_ProcessBLL();
        private Sys_CompanyBLL scb = new Sys_CompanyBLL();
        private Sys_UserBLL sub = new Sys_UserBLL();
        private Sys_DepartmentBLL sdb = new Sys_DepartmentBLL();
        private string StrUserId = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    hidCompanyId.Value = Request.QueryString["dep"].ToString();
                    if (!String.IsNullOrEmpty(hidCompanyId.Value))
                    {
                        Sys_Company sc = scb.GetInfoById(hidCompanyId.Value);
                        hidPCompanyId.Value = sc.CMY_PARENTID.ToString();
                    }

                    //是否勾选中已选人员 1是 0 否
                    string isChoice = Request["Choice"].ToString();
                    //请求勾选的页面
                    string OpenPage = Request["OpenPage"].ToString();
                    if (isChoice == "1")
                    {
                        if (OpenPage.Trim().ToString() == "LockAuthority")
                        {
                            string ProcessId = Request["ProcessId"].ToString();
                            string sql = "select * from yx_authroty t where t.companyid=" + hidCompanyId.Value + " and t.processid= " + ProcessId;
                            DataTable dt = new BaseBLL().Query(sql);

                            if (dt != null && dt.Rows.Count > 0)
                            {
                                for (int i = 0; i < dt.Rows.Count; i++)
                                {
                                    StrUserId += dt.Rows[i]["sysid"].ToString() + ",";
                                }
                            }
                            if (StrUserId.Trim() != "")
                            {
                                if (StrUserId.Trim().ToString().Substring(StrUserId.Trim().Length - 1) == ",")
                                {
                                    StrUserId = "," + StrUserId.Trim().ToString();
                                }
                                else
                                {
                                    StrUserId = "," + StrUserId.Trim().ToString() + ",";
                                }
                            }
                        }
                    }
                    InitData();
                }
                catch (Exception ex)
                {
                    InitData();
                }
            }
        }

        protected void InitData()
        {
            tvProcessUsers.Nodes.Clear();
            DataTable dtCompany = new DataTable();
            if (!String.IsNullOrEmpty(hidCompanyId.Value))
            {
                dtCompany = scb.GetInfoByPId((int)Convert.ToInt32(hidCompanyId.Value));
            }
            else
            {
                dtCompany = scb.GetAllInfo();
            }
            DataTable dtDept = sdb.GetAllInfo();
            DataTable dtUser = sub.GetAllInfo();
            if (dtCompany != null && dtCompany.Rows.Count > 0)
            {
                CreateTree(dtCompany, dtDept, dtUser);
            }
            else
            {
                MessageBox.ResponseScript(this, "alert('【系统提示】无组织机构，请在系统管理平台配置！页面将关闭');window.close()");
            }
        }

        /// <summary>
        /// 定义一个方法 这个方法是用来创建节点
        /// </summary>
        /// <param name="dtCompany">传入的一个公司的dt对象</param>
        /// <param name="dtDepartment">传入的一个节点的dt对象</param>
        /// <param name="dtUser">传入的一个用户的dt对象</param>
        protected void CreateTree(DataTable dtCompany, DataTable dtDept, DataTable dtUser)
        {
            //调用创建公司节点的方法
            CreateCompanyTree(dtCompany, dtDept, dtUser, decimal.Parse(hidPCompanyId.Value), tvProcessUsers, null);
        }

        /// <summary>
        /// 定义一个方法 这个方法是用来创建公司节点的方法
        /// </summary>
        /// <param name="dtCompany">传入的是一个公司的dt对象</param>
        /// <param name="dtDepartment">传入的是一个节点的dt对象</param>
        /// <param name="dtUser">传入的是一个用户的dt对象</param>
        /// <param name="parentID">传入的是一个父节点的ID</param>
        /// <param name="tvProcessUsers">传入的一个TreeView对象</param>
        /// <param name="pNode">传入的i\yige节点ID</param>
        protected void CreateCompanyTree(DataTable dtCompany, DataTable dtDept, DataTable dtUser, decimal parentID, TreeView tvProcessUsers, TreeNode pNode)
        {
            DataRow[] row = dtCompany.Select(" CMY_PARENTID=" + parentID + "");
            for (int i = 0; i < row.Length; i++)
            {
                TreeNode node = new TreeNode();
                if (pNode == null)
                {
                    //绑定节点的值，显示节点名称
                    node.Text = row[i]["CMY_NAME"].ToString() + "【公司】";
                    //给节点显示的名称绑定一个值，这个值为该名称的ID
                    node.Value = row[i]["CMY_ID"].ToString();
                    node.ToolTip = "公司";
                    //设置这个节点是否张开复选框
                    node.ShowCheckBox = false;
                    //设置这个节点是否展开
                    node.Expanded = true;
                    //根据ID得到的节点添加到对应的父节点下面
                    tvProcessUsers.Nodes.Add(node);
                    //用递归来循环创建公司节点
                    CreateCompanyTree(dtCompany, dtDept, dtUser, Convert.ToDecimal(row[i]["CMY_ID"].ToString()), tvProcessUsers, node);
                }
                else
                {
                    //绑定节点的值，显示节点名称
                    node.Text = row[i]["CMY_NAME"].ToString() + "【公司】";
                    //给节点显示的名称绑定一个值，这个值为该名称的ID
                    node.Value = row[i]["CMY_ID"].ToString();
                    node.ToolTip = "公司";
                    //判断是否展开复选框
                    node.ShowCheckBox = false;
                    //判断是否展开节点
                    node.Expanded = true;
                    //根据ID得到的节点添加到对应的父节点下面
                    pNode.ChildNodes.Add(node);
                    //运用递归循环创建公司
                    CreateCompanyTree(dtCompany, dtDept, dtUser, Convert.ToDecimal(row[i]["CMY_ID"].ToString()), tvProcessUsers, node);
                }
                //公司创建完成以后 创建节点
                CreateDepartmentTree(dtDept, dtUser, Convert.ToDecimal(row[i]["CMY_ID"].ToString()), 0, node);
            }
        }

        /// <summary>
        /// 定义一个方法来创建部门
        /// </summary>
        /// <param name="dtDepartment">传入一个部门的Dt对象</param>
        /// <param name="dtUser">传入一个用户的Dt对象</param>
        /// <param name="companyID">传入一个公司的节点的ID</param>
        /// <param name="parentId">传入父节点的ID</param>
        /// <param name="pNode">传入一个TreeNode节点对象</param>
        protected void CreateDepartmentTree(DataTable dtDepartment, DataTable dtUser, decimal companyID, decimal parentId, TreeNode pNode)
        {
            DataRow[] row = dtDepartment.Select("DEPTPARENTID=" + parentId + " and CMY_ID=" + companyID + "");
            for (int i = 0; i < row.Length; i++)
            {
                //实例化一个节点对象
                TreeNode node = new TreeNode();
                //if (decimal.Parse(row[i]["DEPTID"].ToString()) > 19)
                //{
                //    node.Text = row[i]["DEPTNAME"].ToString() + "【井站】";
                //    node.Value = row[i]["DEPTID"].ToString();
                //    node.ToolTip = "井站";
                //}
                //else
                //{
                //创建一个部门信息
                node.Text = row[i]["DEPTNAME"].ToString() + "【部门】";
                node.Value = row[i]["DEPTID"].ToString();
                node.ToolTip = "部门";
                // }

                //判断部门下面是否成一个 复选框
                node.ShowCheckBox = false;
                //判断该节点是否展开
                node.Expanded = false;
                //添加节点
                pNode.ChildNodes.Add(node);
                //运用递归来循环添加部门信息
                CreateDepartmentTree(dtDepartment, dtUser, companyID, Convert.ToDecimal(row[i]["DEPTID"].ToString()), node);

                //创建用户
                CreateUserTree(dtUser, Convert.ToDecimal(row[i]["DEPTID"].ToString()), node);
            }
        }

        /// <summary>
        /// 定义一个方法 这个方法是用来创建用户的
        /// </summary>
        /// <param name="dtUser">传入一个用户的Dt对象</param>
        /// <param name="departmentID">传入一个节点的ID</param>
        /// <param name="pNode">传入一个TreeNode节点对象</param>
        protected void CreateUserTree(DataTable dtUser, decimal companyId, TreeNode pNode)
        {
            DataRow[] row = dtUser.Select(" USER_DEPARTMENT=" + companyId + "");
            for (int i = 0; i < row.Length; i++)
            {
                TreeNode node = new TreeNode();
                //判断这个值是否选择
                if (IsChecked(Convert.ToDecimal(row[i]["USER_ID"].ToString())))
                {
                    node.Text = "<font color='Red'>" + row[i]["USER_NAME"].ToString() + "【用户】" + "</font>";//
                }
                else
                {
                    node.Text = row[i]["USER_NAME"].ToString() + "【用户】";
                }
                //得到节点中的用户
                node.ToolTip = "用户";
                // node.ShowCheckBox = true;
                //判断节点中的是否可以成为复选框
                node.ShowCheckBox = true;
                //初始化节点是否是展开
                node.Expanded = false;

                node.Value = row[i]["USER_ID"].ToString();
                if (StrUserId.Trim().ToString() != "")
                {
                    string userid = row[i]["USER_ID"].ToString();
                    if (userid.Trim().ToString().Substring(0, 1) != ",")
                    {
                        userid = "," + userid;
                    }
                    if (userid.Trim().ToString().Substring(userid.Trim().ToString().Length - 1) != ",")
                    {
                        userid += ",";
                    }
                    if (StrUserId.Contains(userid))
                    {
                        node.Checked = true;
                    }
                    else
                    {
                        node.Checked = false;
                    }
                }
                pNode.ChildNodes.Add(node);
                //if (IsChecked(Convert.ToDecimal(row[i]["sysuserid"].ToString())))
                //{
                //    pNode.Checked = true;
                //    node.Checked = true;
                //    node.Parent.Expand();

                //}
            }
        }

        /// <summary>
        /// 定义一个方法 这个方法是用来选择多个值
        /// </summary>
        /// <param name="userID">传入一个用户ID</param>
        /// <returns>返回一个bool类型</returns>
        protected bool IsChecked(decimal userID)
        {
            bool isTrue = false;
            //string processWorkSql = "select * from tb_processworker where processid=" + hlfdProcessID.Value.Trim() + " and instr(',' || workerid || ',', ',' || " + userID + " || ',', 1) <> 0  ";
            //string workids = string.Empty;
            //DataTable dtProcessWork = OracleHelper.QueryDataTable(processWorkSql, OracleHelper.oraConnStringModelDb);
            ////判断六面是否多选
            //if (dtProcessWork != null && dtProcessWork.Rows.Count > 0)
            //{
            //    isTrue = true;
            //}
            return isTrue;
        }

        protected void tvProcessUsers_SelectedNodeChanged(object sender, EventArgs e)
        {
            TreeNode selectedNode = tvProcessUsers.SelectedNode;

            selectedNode.Selected = false;
            selectedNode.Expand();
            bool checkState = !selectedNode.Checked;
            selectedNode.Checked = checkState;
            //判断选择的节点时候是公司
            if (selectedNode.ToolTip != "公司")
            {
                ChangeChildNodesCheckState(selectedNode.ChildNodes, checkState);
                //判断选择的节点时候是用户
                if (selectedNode.ToolTip == "用户")
                {
                    //调用下面的方法 得到节点中的值
                    ChangeParentNodesCheckState(selectedNode.Parent, checkState);
                }
            }
        }

        protected void ChangeChildNodesCheckState(TreeNodeCollection nodes, bool state)
        {
            if (nodes != null)
            {
                for (int i = 0; i < nodes.Count; i++)
                {
                    nodes[i].Checked = state;
                    ChangeChildNodesCheckState(nodes[i].ChildNodes, state);
                }
            }
        }

        //设置父节点选中或取消状态
        protected void ChangeParentNodesCheckState(TreeNode node, bool state)
        {
            if (node != null && node.Value != "0")
            {
                //判断当前节点是否有多个子节点被选中。如果是，则不处理该节点选中或取消。
                int count = GetChildNodesCheckedCount(node);
                if ((count == 0 && state == false) || (count == 1 && state == true))
                {
                    node.Checked = state;
                }
            }
        }

        protected int GetChildNodesCheckedCount(TreeNode node)
        {
            int count = 0;
            if (node.ChildNodes.Count > 0)
            {
                TreeNodeCollection nodes = node.ChildNodes;
                foreach (TreeNode tmpNode in nodes)
                {
                    if (tmpNode.Checked)
                    {
                        count++;
                    }
                }
            }
            return count;
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            string name = string.Empty;

            //实例化一个StringBuilder 来存储用户ID
            StringBuilder inID = new StringBuilder();

            //得到TreeView对象
            TreeNodeCollection nodes = tvProcessUsers.CheckedNodes;
            int j = 1;

            for (int i = 0; i < nodes.Count; i++)
            {
                //判断选择的是不是一个用户
                if (nodes[i].ToolTip == "用户")
                {
                    if (j == 1)
                    {
                        inID.Append(nodes[i].Value);
                        name = nodes[i].Text.Split('【')[0].ToString();
                        name = name.Replace("<font color='Red'>", "'");
                        name = name + "'";
                    }
                    else
                    {
                        name = name + ",";
                        name = name + nodes[i].Text.Split('【')[0].ToString();
                        name = name.Replace("<font color='Red'>", "'");
                        name = name + "'";
                        inID.Append(",");
                        inID.Append(nodes[i].Value);
                    }
                    j++;
                }
            }

            //当你选择的不是用户
            if (j == 1)
            {
                MessageBox.Show(this, "【系统提示】请选择办理人员！");
            }

            //关闭当前窗口 出现的错是 为定义 参数无效 不支持此熟悉和方法
            name = name.Replace("'", "");

            name += "%" + inID;

            Response.Write("<script> window.returnValue='" + name + "';window.opener=null;window.close();</script>");
        }
    }
}